<!DOCTYPE html>
<html>
<head>
    <title>Canvas Path Test</title>
<meta http-equiv="X-UA-Compatible" content="chrome=1,IE=edge" />
    <script type="text/javascript" src="../x3dom-include.js?full"></script>
    
    <link type="text/css" href="media/css/jquery-ui.css" rel="stylesheet">
	<script type="text/javascript" src="media/js/jscolor.js"></script>
    <script type="text/javascript" src="media/js/jquery.min.js"></script>
    <script type="text/javascript" src="media/js/jquery-ui.min.js"></script>
    
    <script type='text/javascript'>
    
    var mouse_drag_x = 0, mouse_drag_y = 0;
    var last_mouse_drag_x = -1, last_mouse_drag_y = -1;
    var mouse_button = 0;
    var mouse_dragging = false;
    
    var pen_col = "000000";
    var pen_size = 1;
    var bg_col = "#000000";
    
    var userData = {
        shaderProgram: null,
        gl: null
    };     
    
    // Test the gl object received via "context" by rendering a tri in front of all
    function loadShader(gl, shaderType, shaderSource)
    {
         // Create the shader object
         var shader = gl.createShader(shaderType);
         if (shader == 0) return 0;

         // Load the shader source
         gl.shaderSource(shader, shaderSource);

         // Compile the shader
         gl.compileShader(shader);

         return shader;
    }
 
    function init()
    {
        var gl = userData.gl;

        // Setup a vertex and fragment shader and attach it to program
        // put shader source in variables
        var vertexShaderSource = 
         "attribute vec4 vPosition;     \n" +
         "void main()                   \n" +
         "{                             \n" +
         "  gl_Position = vPosition;    \n" +
         "} ";
        var fragmentShaderSource =
        "#ifdef GL_ES             \n" +
        "  precision highp float; \n" +
        "#endif                   \n" +
        "" +
         "uniform float val;            \n" +
         "void main()                   \n" +
         "{                             \n" +
         "  gl_FragColor = vec4(1.0, val, 0.0, 1.0); \n" +
         "} ";

        // create our shaders
        var vertexShader = loadShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
        var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);     

        // Create the shader program object
        var programObject = gl.createProgram();
        if (programObject == 0) return false;

        // Store the shader program in the global user data (which is not 
        // the best solution)
        userData.shaderProgram = programObject;

        // Attach our two shaders to the program
        gl.attachShader (programObject, vertexShader);
        gl.attachShader (programObject, fragmentShader);

        // Link the program
        gl.linkProgram(programObject);
        
        userData.shaderProgram.val = gl.getUniformLocation(userData.shaderProgram, "val");
        
        return true;
    }

    function draw(val)
    {
        var gl = userData.gl;

        var vertices = [ 0.0,  0.5,  0.0,
                        -0.5, -0.5,  0.0,
                         0.5, -0.5,  0.0  ];

        // Set up the viewport
        gl.viewport(0, 0, 256, 256);

        // Clear the depth buffer
        gl.clearColor(0.0, 0.0, 1.0, 1.0);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        // Use the program object we created in init()
        gl.useProgram(userData.shaderProgram);
        
        gl.uniform1f(userData.shaderProgram.val, val);
        
        gl.enableVertexAttribArray(0);

        // Create a buffer for the vertices
        var verticeBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, verticeBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

        // Load the vertex data
        gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);

        // Do the draw, as triangles
        gl.drawArrays(gl.TRIANGLES, 0, 3);
    }
    
    function clearImage(col)
    {
        var myCanvas = document.getElementById("myCanvas");
        
        // redraw the canvas...
        var context = myCanvas.getContext("2d");
        context.fillStyle = col;
        context.fillRect(0, 0, myCanvas.width, myCanvas.height);
        
        context.lineWidth = 1.0;
        context.lineCap = "round";

        //context.beginPath();
        //context.strokeStyle = "#000000";
        //context.strokeRect(0, 0, 256, 256);
        
        myCanvas.parentNode._x3domNode.fieldChanged("url");
        document.getElementById("x3d").render();
    }
    
    function main() 
    {
        var myCanvas = document.getElementById("myCanvas");
        
        initCanvas(myCanvas);
        
        // redraw the canvas...
        var context = myCanvas.getContext("2d");
        context.fillStyle = 'rgb(255,255,255)';
        context.fillRect(0, 0, myCanvas.width, myCanvas.height);
        
        //context.lineWidth = 10.0;
        context.lineCap = "round";

        /*
        context.beginPath();
        // Draw a bounds rect (default color is black)
        context.strokeRect(0, 0, 256, 256);
        context.strokeStyle = "#808080";

        // Draw a vertical line
        context.moveTo(100, 100);
        context.lineTo(100, 200);
        context.stroke();

        // Call beginPath to clear existing state
        context.beginPath();

        // Draw another line
        context.moveTo(200, 100);
        context.lineTo(200, 200);
        context.stroke();
        */
        
        myCanvas.parentNode._x3domNode.fieldChanged("url");
        document.getElementById("x3d").render();
        
        var aCanvas = document.getElementById("aCanvas");
        
        var validContextNames = ['moz-webgl', 'webkit-3d', 'experimental-webgl', 'webgl'];
        
        for (var i=0; i<validContextNames.length && !userData.gl; i++) {
            try {
                userData.gl = aCanvas.getContext(validContextNames[i]);
            }
            catch (e) {}
        }
        
        init();
        draw(1.0);
        
        var sg = document.getElementById("x3d");
        
        setInterval( function() { 
            draw(Math.random());
            // do some sort of "touch" here to invalidate gl objects
            aCanvas.parentNode._x3domNode.fieldChanged("url");
            sg.render();
        }, 100);
    }
    
    function updateImage(canvas)
    {
        var context = canvas.getContext("2d");
        //context.fillStyle = 'rgb(255,255,255)';
        //context.fillRect(0, 0, canvas.width, canvas.height);
        
        if (!mouse_dragging)
            return;
        
        if (last_mouse_drag_x < 0 || last_mouse_drag_y < 0)
        {
            last_mouse_drag_x = mouse_drag_x;
            last_mouse_drag_y = mouse_drag_y;
            return;
        }
        
        // redraw the canvas...
        context.lineWidth = pen_size;

        context.beginPath();
        //context.strokeStyle = "#804020";
        context.strokeStyle = pen_col; //document.getElementById("colorpicker").value;
    
        // Draw a line
        context.moveTo(last_mouse_drag_x, last_mouse_drag_y);
        context.lineTo(mouse_drag_x, mouse_drag_y);
        context.stroke();
        
        canvas.parentNode._x3domNode.fieldChanged("url");
        document.getElementById("x3d").render();
        
        last_mouse_drag_x = mouse_drag_x;
        last_mouse_drag_y = mouse_drag_y;
    }
    
    // add event listeners
    function initCanvas(canvas)
    {
    	canvas.addEventListener('mousedown', function (evt) {
			switch(evt.button) {
				case 0:  mouse_button = 1; break;	//left
				case 1:  mouse_button = 4; break;	//middle
				case 2:  mouse_button = 2; break;	//right
				default: mouse_button = 0; break;
			}
			mouse_drag_x = evt.layerX;
			mouse_drag_y = evt.layerY;
			mouse_dragging = true;
			
			if (evt.shiftKey) { mouse_button = 1; }
			if (evt.ctrlKey)  { mouse_button = 4; }
			if (evt.altKey)   { mouse_button = 2; }
            
            updateImage(canvas);

			window.status='DOWN: '+evt.layerX+", "+evt.layerY;
			evt.preventDefault();
			evt.stopPropagation();
			evt.returnValue = false;
		}, false);
		
		canvas.addEventListener('mouseup', function (evt) {
			mouse_button = 0;
			mouse_dragging = false;
            last_mouse_drag_x = -1;
            last_mouse_drag_y = -1;
            
            updateImage(canvas);
			
			evt.preventDefault();
			evt.stopPropagation();
			evt.returnValue = false;
		}, false);
		
		canvas.addEventListener('mouseout', function (evt) {
			mouse_button = 0;
			mouse_dragging = false;
            last_mouse_drag_x = -1;
            last_mouse_drag_y = -1;
            
            updateImage(canvas);
			
			evt.preventDefault();
			evt.stopPropagation();
			evt.returnValue = false;
		}, false);
		
		canvas.addEventListener('mousemove', function (evt) {
			window.status='MOVE: '+evt.layerX+", "+evt.layerY;
			
			if (!mouse_dragging) {
				return;
            }
			
            mouse_drag_x = evt.layerX;
			mouse_drag_y = evt.layerY;
			
			if (evt.shiftKey) { mouse_button = 1; }
			if (evt.ctrlKey)  { mouse_button = 4; }
			if (evt.altKey)   { mouse_button = 2; }
            
            updateImage(canvas);
			
			evt.preventDefault();
			evt.stopPropagation();
			evt.returnValue = false;
		}, false);
    }
    </script>
    
    <style>
        #ctrlContainer { padding: 0px; width: 280px; }
        #sliderContainer div { float:left; width: 200px;}
        #sliderContainer li { height: 20px;}
        #sliderContainer ul { clear: both; list-style-type: none; margin: 10px 0 10px 0; padding: 0; }
    </style>
    
</head>

<body onload='main();'>
	<div class="group">

    <div style="float:left; width:600px">
    <x3d id="x3d" showStat="false" showLog="false" width="256" height="256">
      <scene>
        <background skyColor='.5 .4 .2'></background>
        <viewpoint position='0 0 5'></viewpoint>
          <shape>
            <appearance>
                <texture hideChildren="false">
                    <canvas width='256' height='256' id='myCanvas' 
                        style="border: solid 1px black; position: absolute; top: -1px; left:256px;">
					</canvas>
                </texture>
                <material diffuseColor='0.6 0.9 0.5'></material>	
            </appearance>
            <sphere></sphere>
         </shape>
      </scene>
    </x3d>

	</div>

    <div style="float:left;">
        <span style="color:olive; font-size:large;">Paint the texture!</span>
        <br>&nbsp;<br>

	    <span onMouseOver="document.getElementById('colPick').color.showPicker();">
	        Choose pen color: <br>&nbsp;<br>
			<input id="colPick" class="color" value="000000" onChange="pen_col = '#'+this.color.toString();">
	    </span>
    
	    <div id="ctrlContainer">
    	    <span>Choose pen size: </span><br>
        	<div id="sliderContainer">
	           	<ul>
    	            <li>
        	        	<span style="width:100px; float:left; clear:both; padding:5px;" id="lSize">1</span>
            	     	<div id="sizeSlider" class="slider"></div>
                	</li>
	            </ul>
    	    </div>
	    </div>


        <div>
            <br>
            <span onMouseOver="document.getElementById('bgcolPick').color.showPicker();">
            Choose background color: <br>&nbsp;<br>
            <input id="bgcolPick" class="color" value="000000" onChange="bg_col = '#'+this.color.toString();" />
            </span>
        <br>&nbsp;<br>
        Clear image with background color: <br>&nbsp;<br>
        <button onClick="clearImage(bg_col);">Reset</button>
        </div>


    </div>

    </div>

    <script>
    $(document).ready(function(){
        
        $(".slider").slider({min: 1, max: 10, step: 1, value: 1, animate: true,
                             range: false, slide: function(e, ui) {
            pen_size = ui.value;
            document.getElementById("lSize").innerHTML = pen_size;
        }});

    });
    </script>
    
</body>

</html>
